import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;

public class NotepadJavaFX extends Application {

    private TextArea textArea;
    private File currentFile;

    @Override
    public void start(Stage primaryStage) {
        // 创建UI组件
        createUI(primaryStage);

        // 设置窗口属性
        primaryStage.setTitle("记事本");
        primaryStage.setWidth(800);
        primaryStage.setHeight(600);
        primaryStage.show();
    }

    private void createUI(Stage stage) {
        BorderPane root = new BorderPane();

        // 创建菜单栏
        MenuBar menuBar = new MenuBar();

        // 文件菜单
        Menu fileMenu = new Menu("文件");
        
        MenuItem newItem = new MenuItem("新建");
        MenuItem openItem = new MenuItem("打开");
        MenuItem saveItem = new MenuItem("保存");
        MenuItem exitItem = new MenuItem("退出");

        // 添加菜单项到文件菜单
        fileMenu.getItems().addAll(newItem, openItem, saveItem, new SeparatorMenuItem(), exitItem);

        // 菜单事件处理
        newItem.setOnAction(e -> newFile());
        openItem.setOnAction(e -> openFile(stage));
        saveItem.setOnAction(e -> saveFile(stage));
        exitItem.setOnAction(e -> System.exit(0));

        // 将菜单添加到菜单栏
        menuBar.getMenus().add(fileMenu);

        // 创建文本区域和滚动面板
        textArea = new TextArea();
        
        // 将菜单栏和文本区域添加到布局中
        root.setTop(menuBar);
        root.setCenter(textArea);

        // 创建场景并设置到舞台
        Scene scene = new Scene(root);
        stage.setScene(scene);
    }

    // 新建文件
    private void newFile() {
        if (confirmSave()) {
            textArea.setText("");
            currentFile = null;
        }
    }

    // 打开文件
    private void openFile(Stage stage) {
        if (confirmSave()) {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择文件");
            fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("文本文件", "*.txt"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
            );
            
            File selectedFile = fileChooser.showOpenDialog(stage);
            
            if (selectedFile != null) {
                try {
                    BufferedReader reader = new BufferedReader(new FileReader(selectedFile));
                    String line;
                    StringBuilder content = new StringBuilder();
                    
                    while ((line = reader.readLine()) != null) {
                        content.append(line).append("\n");
                    }
                    
                    textArea.setText(content.toString().trim());
                    currentFile = selectedFile;
                    reader.close();
                } catch (Exception e) {
                    showError("无法读取文件: " + e.getMessage());
                }
            }
        }
    }

    // 保存文件
    private void saveFile(Stage stage) {
        if (currentFile == null) {
            saveAsFile(stage);
        } else {
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter(currentFile));
                writer.write(textArea.getText());
                writer.close();
            } catch (Exception e) {
                showError("无法保存文件: " + e.getMessage());
            }
        }
    }

    // 另存为
    private void saveAsFile(Stage stage) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("保存文件");
        fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("文本文件", "*.txt"),
            new FileChooser.ExtensionFilter("所有文件", "*.*")
        );
        
        File selectedFile = fileChooser.showSaveDialog(stage);
        
        if (selectedFile != null) {
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter(selectedFile));
                writer.write(textArea.getText());
                writer.close();
                currentFile = selectedFile;
            } catch (Exception e) {
                showError("无法保存文件: " + e.getMessage());
            }
        }
    }

    // 退出前确认是否保存
    private boolean confirmSave() {
        if (!textArea.getText().isEmpty() && currentFile == null) {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("确认");
            alert.setHeaderText("您有未保存的内容");
            alert.setContentText("是否继续?");
            
            ButtonType result = alert.showAndWait().orElse(ButtonType.CANCEL);
            
            return result == ButtonType.OK;
        }
        return true;
    }

    // 显示错误消息
    private void showError(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setContentText(message);
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
